let isEnabled = false;

console.log('[Screenshot Extension] Background script loaded');

// --- START: 读取服务器地址并初始化 UPLOAD_URL 的逻辑 ---

// server_address.ini 文件的路径
const SERVER_ADDRESS_FILE = 'server_address.ini';
// OCR 服务端的 API 基础地址（稍后会被加载的内容替换）
let SERVER_ADDRESS = '';
// 最终的 OCR API 地址，必须使用 let，因为它是异步加载设置的
let UPLOAD_URL = ''; 

/**
 * 从 server_address.ini 文件中读取服务器地址并设置 UPLOAD_URL
 * 增加了对 "server_address=..." 格式的解析逻辑。
 */
async function loadServerAddress() {
  try {
    const fileUrl = chrome.runtime.getURL(SERVER_ADDRESS_FILE);
    const response = await fetch(fileUrl);
    if (!response.ok) {
        throw new Error(`Failed to fetch ${SERVER_ADDRESS_FILE}: ${response.statusText}`);
    }

    // 获取文件内容
    const fileContent = await response.text();
    // 找到包含 "server_address=" 的行，并提取等号后面的值
    let address = '';
    
    // 1. 按行分割文件内容
    const lines = fileContent.split('\n');
    
    for (const line of lines) {
        // 2. 检查该行是否以 "server_address=" 开头（忽略大小写和首尾空格）
        const trimmedLine = line.trim();
        if (trimmedLine.startsWith('server_address=')) {
            // 3. 提取等号后的值，并去除首尾空格
            address = trimmedLine.substring('server_address='.length).trim();
            break; // 找到后立即退出循环
        }
    }
    
    if (address) {
      // 移除尾部可能存在的斜杠，以确保拼接正确
      SERVER_ADDRESS = address.replace(/\/$/, ''); 
      // 拼接 UPLOAD_URL
      UPLOAD_URL = `${SERVER_ADDRESS}/upload_image`; 
      console.log(`[Screenshot Extension] Loaded Server Address: ${SERVER_ADDRESS}`);
      console.log(`[Screenshot Extension] UPLOAD_URL initialized to: ${UPLOAD_URL}`);
    } else {
      console.error(`[Screenshot Extension] Failed to find "server_address=" or value is empty in ${SERVER_ADDRESS_FILE}. Using fallback indicator.`);
      // 使用特殊值作为失败标记
      UPLOAD_URL = 'ERROR_ADDRESS_UNLOADED/upload_image'; 
    }
  } catch (error) {
    console.error(`[Screenshot Extension] Error loading server address from ${SERVER_ADDRESS_FILE}:`, error);
    UPLOAD_URL = 'ERROR_ADDRESS_UNLOADED/upload_image';
  }
}

// 首次加载时调用，确保 UPLOAD_URL 在后续使用前被设置
loadServerAddress();

// --- END: 读取服务器地址并初始化 UPLOAD_URL 的逻辑 ---


// 点击扩展图标时切换状态
chrome.action.onClicked.addListener(async (tab) => {
  isEnabled = !isEnabled;
  
  console.log('[Screenshot Extension] Extension clicked, isEnabled:', isEnabled);
  console.log('[Screenshot Extension] Tab ID:', tab.id);
  
  // 更新图标显示状态
  chrome.action.setTitle({
    tabId: tab.id,
    title: isEnabled ? '区域截图 (已启用)' : '区域截图 (已禁用)'
  });
  
  console.log('[Screenshot Extension] Sending message to content script...');
  
  // 通知 content script
  try {
    const response = await chrome.tabs.sendMessage(tab.id, {
      action: 'toggleScreenshot',
      enabled: isEnabled
    });
    console.log('[Screenshot Extension] Content script response:', response);
  } catch (error) {
    console.error('[Screenshot Extension] Error sending message to content script:', error);
    console.error('[Screenshot Extension] This might mean content script is not loaded. Try refreshing the page.');
  }
});

// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('[Screenshot Extension] Message received in background:', request);
  console.log('[Screenshot Extension] Sender:', sender);
  
  if (request.action === 'captureScreenshot') {
    console.log('[Screenshot Extension] Capture screenshot request received');
    console.log('[Screenshot Extension] Area:', request.area);
    
    // 异步处理截图、上传和通知，并立即发送响应
    captureAndUploadAndNotify(sender.tab.id, request.area)
      .then(() => {
        console.log('[Screenshot Extension] Screenshot and OCR process completed successfully');
      })
      .catch(error => {
        console.error('[Screenshot Extension] Screenshot and OCR process failed:', error);
      });
    
    // 立即发送响应以防止端口关闭错误
    sendResponse({ success: true, message: 'Screenshot and OCR started' });
  }
  
  return true; // 保持消息通道开放
});


/**
 * 截图、裁剪、上传并通知
 * 移除了本地下载功能
 */
async function captureAndUploadAndNotify(tabId, area) {
  let croppedDataUrl = null;
  try {
    console.log('[Screenshot Extension] captureAndUploadAndNotify called');
    
    // 1. 截取整个标签页
    console.log('[Screenshot Extension] Capturing visible tab...');
    const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: 'png' });
    
    // 2. 裁剪图片
    console.log('[Screenshot Extension] Cropping image...');
    croppedDataUrl = await cropImage(dataUrl, area);
    
    // 3. 上传图片进行 OCR 识别 (移除了本地下载步骤)
    console.log('[Screenshot Extension] Uploading image for OCR...');
    await uploadImageAndNotify(croppedDataUrl);
    
  } catch (error) {
    console.error('[Screenshot Extension] Error in captureAndUploadAndNotify:', error);
    throw error; 
  }
}

/**
 * 将 Data URL 图片上传到 OCR 服务器并显示通知
 * @param {string} dataUrl - 裁剪后的图片的 Data URL
 */
async function uploadImageAndNotify(dataUrl) {
    // 关键：检查 UPLOAD_URL 是否有效，是否包含错误标记
    if (UPLOAD_URL.includes('ERROR_ADDRESS_UNLOADED')) {
        const errorMessage = 'OCR UPLOAD_URL 未成功加载。请确保 server_address.ini 文件存在于插件目录，且包含正确的 server_address=... 键值对。';
        console.error('[Screenshot Extension] ' + errorMessage);
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icon.png',
            title: '❌ OCR 上传失败',
            message: errorMessage
        });
        return; // 提前退出
    }

    try {
        // 1. 将 Data URL 转换为 Blob 对象
        const response = await fetch(dataUrl);
        const blob = await response.blob();
        
        // 2. 构造 FormData
        const formData = new FormData();
        // 设置文件名，服务器可能需要一个文件名
        formData.append('file', blob, 'screenshot.png'); 
        
        console.log('[Screenshot Extension] Sending POST request to OCR server at:', UPLOAD_URL);

        // 3. 发送 POST 请求到 OCR 服务端
        const uploadResponse = await fetch(UPLOAD_URL, {
            method: 'POST',
            body: formData
        });
        
        // 4. 解析 JSON 响应
        const data = await uploadResponse.json();

        // 5. 根据响应内容决定通知内容
        let title = 'OCR 识别结果';
        let message = '无法获取识别结果。';
        let recognizedText = '未识别到文字。';

        if (uploadResponse.ok && data.code === 200) {
            title = '✅ 识别成功';
            recognizedText = data.recognized_text || '未识别到任何文字。';
            // 为了防止通知内容过长，只显示前150个字符
            message = recognizedText.substring(0, 150) + (recognizedText.length > 150 ? '...' : '');
        } else {
            title = `❌ 识别失败 (Code: ${data.code || uploadResponse.status})`;
            message = data.message || `网络或服务端错误。状态码: ${uploadResponse.status}`;
            recognizedText = message; // 错误信息作为详情
        }
        
        console.log('[Screenshot Extension] OCR Result:', recognizedText);

        // 6. 显示通知
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icon.png', // 使用插件图标
            title: title,
            message: message,
            contextMessage: recognizedText.length > 150 ? '点击查看完整识别结果' : ''
        });

    } catch (error) {
        console.error('[Screenshot Extension] Error in uploadImageAndNotify:', error);
        
        // 网络或解析失败时显示错误通知
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icon.png',
            title: '❌ OCR 上传失败',
            message: `无法连接到服务器或处理响应: ${error.message}. 请检查服务器地址是否正确或服务器是否运行。`
        });
    }
}


// 裁剪图片 (此函数保持不变)
async function cropImage(dataUrl, area) {
  console.log('[Screenshot Extension] cropImage started');

  try {
    // 1. 使用 fetch 将 dataUrl 转换为 Blob
    const response = await fetch(dataUrl);
    const blob = await response.blob();

    // 2. 使用 Service Worker 支持的 createImageBitmap 从 Blob 创建 ImageBitmap
    const imageBitmap = await createImageBitmap(blob);
    
    console.log('[Screenshot Extension] Image loaded (ImageBitmap), size:', imageBitmap.width, 'x', imageBitmap.height);
    console.log('[Screenshot Extension] Crop area:', area);

    // 确保裁剪区域在图片范围内
    const cropX = Math.max(0, Math.min(area.x, imageBitmap.width));
    const cropY = Math.max(0, Math.min(area.y, imageBitmap.height));
    const cropWidth = Math.min(area.width, imageBitmap.width - cropX);
    const cropHeight = Math.min(area.height, imageBitmap.height - cropY);
    
    console.log('[Screenshot Extension] Adjusted crop area:', { 
      x: cropX, 
      y: cropY, 
      width: cropWidth, 
      height: cropHeight 
    });
    
    // 3. 使用 OffscreenCanvas 进行绘制和裁剪
    const canvas = new OffscreenCanvas(cropWidth, cropHeight);
    const ctx = canvas.getContext('2d');
    
    console.log('[Screenshot Extension] Canvas created:', cropWidth, 'x', cropHeight);
    
    // 裁剪指定区域
    ctx.drawImage(
      imageBitmap,
      cropX, cropY, cropWidth, cropHeight,
      0, 0, cropWidth, cropHeight
    );
    
    console.log('[Screenshot Extension] Image drawn to canvas');
    
    // 4. 转换为 blob 然后转为 data URL
    const finalBlob = await canvas.convertToBlob({ type: 'image/png' });
    console.log('[Screenshot Extension] Blob created, size:', finalBlob.size);
    
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        console.log('[Screenshot Extension] Blob converted to data URL');
        resolve(reader.result);
      };
      reader.onerror = (error) => {
        console.error('[Screenshot Extension] FileReader error:', error);
        reject(error);
      };
      reader.readAsDataURL(finalBlob);
    });
    
  } catch (error) {
    console.error('[Screenshot Extension] Image/Canvas processing error (in cropImage):', error);
    throw error; // 向上抛出错误
  }
}